<template>
  <div></div>
</template>

<script setup>
import { onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useProConfig } from '/@/stores/proConfig';
import {useLoginApi} from "/@/api/login";
import {Session} from "/@/utils/storage";
import Cookies from "js-cookie";
import { ElMessage } from 'element-plus';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import {NextLoading} from "/@/utils/loading";
// 引入 api 请求接口
const useLogin = useLoginApi();

const proConfig= useProConfig();
const { config } = storeToRefs(proConfig);
const {wxredirect_uri} = config.value;
const route = useRoute();
const router = useRouter();

const userLoginByCode = ()=>{
  const postData = {
    wxcode : route.query.code,
  }
  useLogin.signInWx(postData).then(async (res)=>{
    const {data} = res;
    const accessToken = data['X-Token']
    if(accessToken){
      Session.set('token', accessToken);
      // 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
      Cookies.set('userName', data['userName']);
      // 前端控制路由，2、请注意执行顺序
      const isNoPower = await initFrontEndControlRoutes();
      if (isNoPower) {
        NextLoading.done(200);
        ElMessage.warning('抱歉，您没有登录权限');
        Session.clear();
      }else{
        const signInText = '欢迎回来！';
        ElMessage.success(`${signInText}`);
        router.push('/');
      }
    }else{
      ElMessage.error(`ATUTH2接口异常，未正确返回token...`);
    }
  }).catch(error =>{
    alert(error)
  })
}

onMounted(()=>{
  //解决#号问题  http://www.iraetaforging.cn:8281/report/?code=wi2OWAN8h6tOksVm7-OiTJ6aVDal89nrtfIcHjjqEW8&state=STATE#/wxcode
  const url = window.location.href
  const code = url.match(/=(\S*)&state=STATE#/)
  if (code !== null) {
    // 如果能获得code，说明需要处理url并跳转，如果不能获得code，不用处理
    const replaceUrl = wxredirect_uri + '?code=' + code[1] + '&state=STATE'
    console.log(replaceUrl)
    return window.location.replace(replaceUrl)
  } else {
    userLoginByCode()
  }
})
</script>

<style scoped>

</style>
